import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useDebounce } from '@cfe/hooks';
import { message, Modal } from 'antd';
import { decamelizeKeys } from 'humps';
import { useSearchParams, useSelector } from 'umi';

import Number from '@/components/Number';
import { requestWithoutCache } from '@/utils/request';

import GroupTagModalContent from './GroupTagModalContent';
import { SELECTOR_TYPES } from './TagSelectorFilter';
const initTag = {
  groupId: '',
  groupName: '',
  description: '',
  customType: '',
  value: {},
};
const GroupTagModal = (props) => {
  const {
    groupTagInfo = {},
    clearGroupTagInfo = () => {},
    selectGroupTag,
    dimId,
    visible,
    onClose,
    propsGroupTagInfo = {}, // 此数据是从搜索框而来 搜索点击后打开弹窗 获取数据等
  } = props;
  const { groupId, groupName, description, customType, value } =
    groupTagInfo || propsGroupTagInfo || initTag;
  const [groupTagData, setGroupTagData] = useState(null);
  const [coverageData, setCoverageData] = useState(null);
  const { coverage, rate, p_date } = coverageData || {};
  const dispatch = useDispatch();
  const contentRef = useRef();
  const [searchParams] = useSearchParams();
  const crowd_id = searchParams.get('crowd_id');
  const groupTag = useSelector((state) => state.label.groupTag);
  //todo 此处想动 原因是接口的触发关联性太弱了  不是自己写的代码很难想到在这里  查找问题复杂度增加  建议提到点击添加按钮的时候去发 然后将结果数据传进来
  useEffect(() => {
    // 此处由于广告投放转化人群不需要这个接口 做了一个兼容处理  此处groupId === 9999999 && customType === 9 均可 后期看业务扩展可调整
    if ([9, 10, 11, 12].includes(customType)) {
      setGroupTagData(value);
      return;
    }
    if (groupId && groupTag) {
      dispatch({
        // /api/dmp/market/tag?group_id=xxx   获取tag信息
        type: 'label/loadGroupTagFilterInfo',
        payload: {
          groupTagId: groupId,
          callback: (data) => {
            // 此处由于广告投放转化人群不需要这个接口 所以对null返回做了一个兼容处理
            if (data && data.length > 0) {
              setGroupTagData(data);
            }
          },
        },
      });
    }
  }, [customType, dispatch, groupId, groupTag, value]);

  const handleClearInfo = () => {
    setGroupTagData(null);
    contentRef.current?.form.resetFields();
    clearGroupTagInfo(null);
    onClose();
  };

  useEffect(() => {
    // 关闭 modal 的时候清理一下 coverage
    setCoverageData(null);
  }, [groupId]);

  const requestCoverage = useDebounce(() => {
    if (!groupTagData) return;
    const form = contentRef.current.form;
    return form
      .validateFields()
      .then(() => {
        setCoverageData(null);
        return requestWithoutCache(`/api/dmp/crowd/coverage`, {
          body: JSON.stringify({
            type: 'tag',
            group_id: +groupId,
            tags: groupTagData
              .map((groupTagDataItem) => {
                const { id: tagId, required } = groupTagDataItem;
                const valueItem = {};
                const value = form.getFieldsValue();
                if (!value[tagId] && !required) return {};
                if (groupTagDataItem.tagType === SELECTOR_TYPES.ENUM) {
                  valueItem.tagValues = value[tagId].map(
                    ({ tagDataId: valueId, value: valueText }) => {
                      return { valueId, valueText };
                    },
                  );
                }

                if (groupTagDataItem.tagType === SELECTOR_TYPES.TEXT) {
                  valueItem.tagValues = value[tagId].map((value) => {
                    const { label: valueText, value: valueId } = value;
                    return { valueId, valueText };
                  });
                }

                if (groupTagDataItem.tagType === SELECTOR_TYPES.DATERANGE) {
                  const [start, end] = value[tagId];
                  valueItem.dateFrom = start;
                  valueItem.dateTo = end;
                }

                if (groupTagDataItem.tagType === SELECTOR_TYPES.NUMBER) {
                  valueItem.number = value[tagId];
                }

                if (groupTagDataItem.tagType === SELECTOR_TYPES.RANGE) {
                  valueItem.numberFrom = value[tagId][0];
                  valueItem.numberTo = value[tagId][1];
                }

                if (groupTagDataItem.tagType === SELECTOR_TYPES.Tree) {
                  valueItem.tagValues = value[tagId].map(
                    ({ tagDataId: valueId, value: valueText }) => {
                      return { valueId, valueText };
                    },
                  );
                }

                if (groupTagDataItem.tagType === SELECTOR_TYPES.WithCoverage) {
                  valueItem.tagValues = value[tagId].map(
                    ({ tagDataId: valueId, value: valueText }) => {
                      return { valueId, valueText };
                    },
                  );
                }

                const result = {
                  ...groupTagDataItem,
                  tagId,
                  ...valueItem,
                };

                delete result.check_data;
                return decamelizeKeys(result);
              })
              .filter(Boolean),
          }),
          method: 'POST',
        });
      })
      .then((res) => {
        const { data } = res;
        if (data) {
          setCoverageData(data);
        }
      })
      .catch((error) => {
        // eslint-disable-next-line no-console
        console.error(error);
      });
  }, 1000);

  useEffect(() => {
    if (groupTagData) {
      requestCoverage();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleValuesChange = () => {
    requestCoverage();
  };

  useEffect(() => {
    if (customType === 1) {
      selectGroupTag({
        groupId,
        dimId: dimId ?? propsGroupTagInfo.dimId,
        groupTagInfo: groupTagInfo ?? propsGroupTagInfo,
        ...groupTagInfo,
        ...propsGroupTagInfo,
        crowdId: crowd_id,
      });
      handleClearInfo();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [groupId]);

  // 此变量用于区分 是否是 广告投放转化人群弹窗 点击路径 标签筛选> 用户筛选 > 广告投放转化人群
  //todo 广告投放转化人群 此处groupId === 9999999 && customType === 9 均可 后期看业务扩展可调整
  const isAdTransformPeople = customType === 9;
  const isDduTransformPeople = [10, 11, 12].includes(customType);

  const style = {};
  if (
    (groupTagData &&
      Array.isArray(groupTagData) &&
      groupTagData?.find((item) => item.tagType === 8)) ||
    isAdTransformPeople
  ) {
    style.width = '700px';
  }
  return (
    <Modal
      title={groupName}
      // open={Boolean(groupTagData)}
      open={visible} // todo 搜索处的弹出处理  相关数据 propsGroupTagInfo
      maskClosable={false}
      {...style}
      destroyOnClose
      onOk={() => {
        return contentRef.current.form.validateFields().then(() => {
          const value = contentRef.current.form.getFieldsValue();
          selectGroupTag({
            groupTagData,
            groupId,
            dimId: dimId ?? propsGroupTagInfo.dimId,
            ...groupTagInfo,
            ...propsGroupTagInfo,
            value,
            // value: tempValue,
            groupTagInfo: groupTagInfo ?? propsGroupTagInfo,
            crowdId: crowd_id,
          });
          handleClearInfo();
          message.success('标签添加成功');
        });
      }}
      onCancel={handleClearInfo}
    >
      <div style={{ marginBottom: '10px' }}>{description}</div>
      <div style={{ marginBottom: '10px' }}>标签选项</div>
      <GroupTagModalContent
        customType={customType}
        groupTagData={groupTagData}
        ref={contentRef}
        onValuesChange={handleValuesChange}
        groupId={groupId}
        isAdTransformPeople={isAdTransformPeople}
        isDduTransformPeople={isDduTransformPeople}
        coverage={coverage}
        rate={rate}
        value={value}
      />

      <div style={{ marginTop: '30px' }}>
        <h3>当前标签详情 </h3>
        <p style={{ marginBottom: '5px' }}>
          {`当前的使用数据日期为: ${p_date || '-'}`}{' '}
        </p>
        {isAdTransformPeople || isDduTransformPeople ? (
          <div>由于标签特性，无法实时展示覆盖人数，可在生成人群包后查看</div>
        ) : (
          <div style={{ display: 'flex' }}>
            <div style={{ marginRight: '20px' }}>
              覆盖人数：{<Number showTip format="short" value={coverage} />} 人{' '}
            </div>
            <div>覆盖度：{rate ?? '-'}</div>
          </div>
        )}
      </div>
    </Modal>
  );
};

export default GroupTagModal;
